/**
 * 常用方法封装 请求，文件上传等
 * @author echo. 
 **/
 let innerAudioContext = uni.createInnerAudioContext();
const tui = {
	//接口地址
	interfaceUrl: function() {
		// return 'http://rabbit.rjzmpp.com/data/'
		// return 'http://shop.wyc168.com/api/'
		return 'https://nutrition.mmj.miaojian1688.com/data/'
	},
	faceUrl: function() {
		// return 'http://rabbit.rjzmpp.com/data/'
		return 'https://mohe.huangshijinhong.com/'
	},
	toast: function(text, duration, success) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
	modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
		uni.showModal({
			title: '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: "#555",
			confirmColor: confirmColor || "#5677fc",
			confirmText: confirmText || "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	isAndroid: function() {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() == "android"
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	delayed: null,
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request: function(url, method, postData, isDelay, isForm, hideLoading) {
		//接口请求
		let loadding = false;
		tui.delayed && uni.hideLoading();
		clearTimeout(tui.delayed);
		tui.delayed = null;
		if (!hideLoading) {
			tui.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}
		// console.log(url)
		// uni.setStorageSync("d_token", '7bb6ab1cf1222d6491038f5017964a06')
		return new Promise((resolve, reject) => {
			uni.request({
				url: tui.interfaceUrl() + url,
				data: postData,
				header: {
					// 'content-Type': 'application/json',
					'content-type':'application/x-www-form-urlencoded',
					'authorization': tui.getToken(),
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					console.log(res)
					clearTimeout(tui.delayed)
					tui.delayed = null;
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					if(res.data.code==1){
						resolve(res.data)
					} else if (res.data.code ==401) {
						tui.toast(res.data.info)
						uni.removeStorageSync('d_token')
						uni.removeStorage({
						    key: 'd_token',
						    success: function (res) {
						        console.log('success');
						    }
						});
						// tui.wetLogin()
						setTimeout(function(){
							uni.redirectTo({
								url: '/pages/login/login'
							})
						},1000)
						return
					}else if(res.data.code==404){
						tui.toast(res.data.info)
						setTimeout(function(){
							tui.href('/pages/address/eit_address')
						},1000)
					}else if(res.data.code==0){
						tui.toast(res.data.info)
					}
				},
				fail: (res) => {
					clearTimeout(tui.delayed)
					tui.delayed = null;
					tui.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(url, src) {
		let that = this
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: tui.interfaceUrl() + url,
				filePath: src,
				name: 'file',
				header: {
					'authorization':  tui.getToken(),
				},
				success: function(res) {
					uni.hideLoading()
					let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					console.log(d)
					let fileObj = d;
					resolve(fileObj)
				},
				fail: function(res) {
					reject(res)
					that.toast(res.msg);
				}
			})
		})
	},
	tuiJsonp: function(url, callback, callbackname) {
		// #ifdef H5
		window[callbackname] = callback;
		let tuiScript = document.createElement("script");
		tuiScript.src = url;
		tuiScript.type = "text/javascript";
		document.head.appendChild(tuiScript);
		document.head.removeChild(tuiScript);
		// #endif
	},
	//设置用户信息
	setUserInfo: function(mobile,token) {
		//uni.setStorageSync("thorui_token", token)
		uni.setStorageSync("thorui_mobile", mobile)
	},
	wetLogin(){
		let that = this
		uni.getUserProfile ({
			desc: '登录后可同步数据',
			success: async (obj) => {
			console.log('obj', obj);
				// 调用 action ，请求登录接口
				// await this.login(obj);
				uni.login({
					provider: 'weixin',
					success: (res) => {
						let data = {code: res.code,inviter_code:uni.getStorageSync('refCode'),iv:obj.iv,encrypted:obj.encryptedData}
						tui.request("api.wxapp/decode", "POST", data, false, false, true).then((res) => {
							console.log(res)
							
							uni.removeStorage({
							    key: 'refCode',
							    success: function (res) {
							        console.log('success');
							    }
							});
							uni.setStorageSync('d_token', res.data.token)
							uni.$emit("isLogin",1)
							if(res.data.is_avatar==2){
								console.log(res.data.is_avatar)
								uni.$emit("isShow",res.data.is_avatar)
							}else{
								tui.toast(res.info)
							}
						}).catch((res) => {
							that.is_btn = false
						})
					},
				});
			},
			fail: () => {
				uni.showToast({
					title: '授权已取消',
					icon: 'error',
					mask: true,
				});
			},
			complete: () => {
				// 隐藏loading
				uni.hideLoading();
			},
		});
	},
	//获取token
	getToken() {
		return uni.getStorageSync("d_token")
	},
	//判断是否登录
	isLogin: function() {
		return uni.getStorageSync("d_token") ? true : false
	},
	//跳转页面，校验登录状态
	href(url, isVerify) {
		if (isVerify && !tui.isLogin()) {
			uni.navigateTo({
				url: '/pages/common/login/login'
			})
		} else {
			uni.navigateTo({
				url: url
			});
		}
	},
	dianji(fn) {
	    let that = this;
		let is_true = getApp().globalData.is_true
		console.log(is_true)
	    if (is_true) {
	        getApp().globalData.is_true = false;
	        setTimeout(function () {
	            getApp().globalData.is_true = true;
	        }, 5000)
			fn();
	    } else {
	        //如果一直走else分支可能是你没有在页面的data下面挂载onoff:true,不然一直都会走else
	        console.log("请稍后点击")
	    }
	},
	phoneYin(phone){
		if(phone){
			return  phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
		}
	},
	phoneMore(phone){
		var arr = phone.split(',')
		var data =''
		arr.map((item,index)=>{
			data = data+item.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')+','
		})
		data = data.slice(0, -2)
		if(phone){
			return  data;
		}
	},
	setIncrement(val) {
	    let status = false,
	    step = 3.30* val / (1000 / 30),
	    count  = 0,
	    interval = null;
	    interval = setInterval(() => {
	        if(count < val) {
	            count = count + step;
	        } else {
	            status = true
				count = val
	        }
	        if(status) {
	            clearInterval(interval)
	        }
			return count
	    }, 30)
		
	},
	// 播放音频
	playVoice () {
		
		let datapath =uni.getStorageSync("mp3")
		let i = 0
	  innerAudioContext.src = datapath[i];
	  // innerAudioContext.loop = true;
	  // innerAudioContext.obeyMuteSwitch = false;
	  innerAudioContext.play();
	  innerAudioContext.onPlay(() => {
	    console.log('开始播放');
		uni.$emit('bofang', true)
	  });
	  innerAudioContext.onPause(() => {
	    console.log('播放停止');
	  		uni.$emit('bofang', false)
	  });
	  innerAudioContext.onEnded(()=>{
		   console.log('播放结束');
		  i++
		  console.log(i)
		  console.log(datapath.length)
		  if(i==datapath.length){
			  i = 0
		  }
		  console.log(datapath[i])
		  innerAudioContext.src = datapath[i];
		  innerAudioContext.play();
	  })
	  innerAudioContext.onError((res) => {
	    innerAudioContext.destroy();
	    return;
	    uni.showToast({
	      title: '音效播放错误 ->' + JSON.stringify(res),
	      icon: 'none',
	    });
	  });
	},
	// 停止播放
	stopVoice () {
	  innerAudioContext.pause();
	},
	startVoice () {
	  innerAudioContext.play()
	  
	},
}

export default tui